import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Image} from '@tarojs/components';
import {AtButton} from 'taro-ui';
import {H5_LOGIN, NEW_ORDER_DETAIL, NEW_ORDER_PAY, RESOURCE_URL, TARO_ENV} from '../../constants/api';
import {GetRequest} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import {payment} from "../../utils/payment.service";
import {newHttp} from "../../utils/request";
import './wallet.scss';

type PageState = {
  orderNum: string
  userId: string
  redirectUrl: string
  payAmount: number
}

export default class Wallet extends Component {
  state: PageState = {
    userId: '',
    redirectUrl: '',
    orderNum: '',
    payAmount: 0
  }

  async componentDidShow() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const {orderNum = '', userId = ''} = Taro.getCurrentInstance().router.params
    Taro.showLoading({title: '加载中...'})
    const res = await newHttp.post(NEW_ORDER_DETAIL + orderNum, {userId});
    let payAmount = 0
    if (res.data) {
      payAmount = res.data.pay_amount
      Taro.hideLoading()
    }
    this.setState({payAmount, orderNum, userId, redirectUrl: res.data.redirect_url})
    wx.miniProgram.getEnv((res) => {
      if (res.miniprogram) {
        wx.miniProgram.redirectTo({
          url: "/distributor/wallet/pay?orderNum=" + orderNum + '&userId=' + userId       //小程序的支付地址，queryParam是需要传递的商品id等数据
        })
        return false;
      }
    })
  }

  async pay() {
    const {payAmount, orderNum, userId, redirectUrl} = this.state
    if (payAmount > 0) {
      const result = await newHttp.post(NEW_ORDER_PAY + orderNum, {userId});
      if (result.data) {
        const payRet = await payment.payment(result.data, false)
        if (!payRet) {
          return
        } else {
          Taro.showToast({title: '支付成功', icon: 'success'})
          setTimeout(() => {
            Taro.redirectTo({ url: '/main/webview/index?notCarryToken=1&url=' + redirectUrl })
          }, 1500)
        }
      }
    }
  }


  render() {
    const {payAmount} = this.state
    return (
      <View className='wallet-root'>
        <View className='head'>
          <Image className='iconImg' src={RESOURCE_URL + "/resources/weapp/images/cashout-icon.png"} mode='aspectFill'/>
          <View className='title'>支付金额</View>
          <View className='num total'><Text>￥</Text>{payAmount}</View>
        </View>
        {payAmount > 0 ? <View className='btn-box tadpole' onClick={this.pay.bind(this)}>
          <View className='btn-style' style={`background-color: ${process.env.mainColor};font-size:18px;`}>支付</View>
        </View> : <View className='btn-box tadpole'>
          <AtButton type='secondary'>支付</AtButton>
        </View>}
      </View>
    );
  }
}
